﻿using LdtDataEngin.ModuleDetail.BaseModule.MultiFack;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.Dudection;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CommonModule.PersonMerger
{
    /// <summary>
    /// 证据要素的认定和待认定合并
    /// </summary>
    public class EvidElementMerge
    {
        //将分人员证据进行合并后的数据内容存储
        //数据标识<诉讼地位，人员名称>,<认定状态，合并后xml>
        private Dictionary<Tuple<string, string>, List<Tuple<string, XmlNode>>> mergeEvidXml = new Dictionary<Tuple<string, string>, List<Tuple<string, XmlNode>>>();
        private DataContext dataContext { get; }
        ///<summary>
        /// 案由集合
        ///</summary> 
        private List<CaseCauseModel> CaseCausesList { get; }
        public EvidElementMerge(DataContext dataContextIn) 
        {
            dataContext = dataContextIn;
            CaseCausesList = dataContext.DataLayerAns.CaseCausesList;
        }
        /// <summary>
        /// 进行认定证据合并
        /// </summary>
        /// <param name="nodetemplate">模板节点</param>
        /// <param name="xmlConfigModels">合并配置</param>
        /// <param name="nodeHandleType">同节点判定模式</param>
        /// <returns></returns>
        public XmlNode EvidMerge(XmlNode nodetemplate, List<SameNodeXml> xmlConfigModels, MultiFactBase.SameNodeHandleType nodeHandleType,string type)
        {
            Dictionary<Tuple<string, string>, List<Tuple<string, string>>> eviddata = LoadEvidData();
            MultiFactUnion multiFactunion = new MultiFactUnion();
            //分人员证据认定和待认定分别合并
            foreach (var evidvalue in eviddata)
            {
                //遍历原告方和被告方的证据
                //根据证据认定类型进行分组
                var diclist = evidvalue.Value.GroupBy(ke => ke.Item1).ToDictionary(a => a.Key, b => b.ToList());
                XmlDocument result = new XmlDocument();
                result.LoadXml(string.Format("<{0}></{0}>", nodetemplate.ParentNode.Name));
                XmlNode xmlNodeFact = result.CreateElement("事实要素");
                result.DocumentElement.AppendChild(xmlNodeFact);
                foreach (var rows in diclist)
                {//分别将认定和待认定的证据进行合并

                    xmlNodeFact.RemoveAll();
                    XmlNode newNode = result.Clone();
                    foreach (var row in rows.Value)
                    {
                        if (!string.IsNullOrWhiteSpace(row.Item1) && !string.IsNullOrWhiteSpace(row.Item2))
                        {
                            xmlNodeFact.RemoveAll();
                            XmlDocument xmlnode = new XmlDocument();
                            xmlnode.LoadXml(row.Item2);
                            multiFactunion.MultiFactUnionXml(nodetemplate, newNode, xmlnode, xmlConfigModels, xmlNodeFact, nodeHandleType);
                            newNode = result.Clone();
                        }
                    }
                    xmlNodeFact.RemoveAll();
                    multiFactunion.MultiFactUnionXml(nodetemplate, newNode, newNode, xmlConfigModels, xmlNodeFact, nodeHandleType);
                    dataContext.InteractiveShow.LogShow("\r\n----------★" + evidvalue.Key.Item1 + "(" + evidvalue.Key.Item2 + ") 认定状态：" + rows.Key + " 合并后的内容为：★----------\r\n" + result.OuterXml);
                    if (!mergeEvidXml.ContainsKey(evidvalue.Key))
                    {
                        List<Tuple<string, XmlNode>> tuples = new List<Tuple<string, XmlNode>>();
                        tuples.Add(new Tuple<string, XmlNode>(rows.Key, result.Clone()));
                        mergeEvidXml.Add(evidvalue.Key, tuples);
                    }
                    else
                    {
                        mergeEvidXml[evidvalue.Key].Add(new Tuple<string, XmlNode>(rows.Key, result.Clone()));
                    }

                }
            }
            //将原告方认定的证据和被告方认定的证据合并
            XmlDocument document = new XmlDocument();
            document.LoadXml(string.Format("<{0}></{0}>", nodetemplate.ParentNode.Name));
            XmlNode xmlNodeFactt = document.CreateElement("事实要素");
            document.DocumentElement.AppendChild(xmlNodeFactt);
            XmlNode newNodetemp = document.Clone();
            foreach (var person in mergeEvidXml.Values)
            {
                var personxml = person.Where(iscon => iscon.Item1 == type).ToList();
                foreach (var tupxml in personxml)
                {
                    xmlNodeFactt.RemoveAll();
                    multiFactunion.MultiFactUnionXml(nodetemplate, newNodetemp, tupxml.Item2, xmlConfigModels, xmlNodeFactt, nodeHandleType);
                    newNodetemp = document.Clone();
                }

            }

            dataContext.InteractiveShow.LogShow("\r\n----------★证据最终认定为：★----------\r\n" + document.OuterXml);
            return document;
        }

        /// <summary>
        /// 获取证据的认定和带人分人员数据
        /// </summary>
        /// <param name="isconfirm">1认定，0待认定</param>
        /// <returns></returns>
        public Dictionary<Tuple<string, string>, XmlNode> GetEvidPersonxml(string isconfirm)
        {
            Dictionary<Tuple<string, string>, XmlNode> valuePairs = new Dictionary<Tuple<string, string>, XmlNode>();
            foreach (var per in mergeEvidXml)
            {
                foreach (var row in per.Value)
                {
                    if (row.Item1 == isconfirm)
                    {
                        valuePairs.Add(per.Key, row.Item2);
                    }
                }
            }
            return valuePairs;
        }


        #region 加载证据所需的内容
        /// <summary>
        /// 加载证据数据
        /// </summary>
        /// <returns></returns>
        private Dictionary<Tuple<string, string>, List<Tuple<string, string>>> LoadEvidData()
        {
            Dictionary<Tuple<string, string>, List<Tuple<string, string>>> evidData = new Dictionary<Tuple<string, string>, List<Tuple<string, string>>>();
            List<DataModel> dataModelRootList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.XmlPath.IndexOf("证据/详情") > -1 && a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名") != null)?.ToList();
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = this.dataContext };
            foreach (DataModel dataModel in dataModelRootList)
            {
                string name = dataModel.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                string suitid = dataModel.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                Tuple<string, string> keyper = new Tuple<string, string>(suitid,name);
                //证据内容空节点
                List<DataModel> dataModelEvidenceList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModel);
                List<DataModel> dataModelDetailsList = dataModelEvidenceList.Where(a => a.XmlPath.IndexOf("详情") > -1 && a.AttributesList.FirstOrDefault(b => b.Name == "认定状态") != null)?.ToList();
                if (dataModelDetailsList != null && dataModelDetailsList.Count > 0)
                {
                    foreach (DataModel dataModelDetails in dataModelDetailsList)
                    {
                        //内容不为空
                        if (dataModelDetails.AttributesList.FirstOrDefault(a => a.Name == "认定状态") != null)
                        {
                            List<DataModel> dataModelFactorList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerOpt.SourdatModleList, dataModelDetails);
                            if (dataModelFactorList.FirstOrDefault(a => a.XmlPath == "/证据要素" ||  a.XmlPath== "证据要素"  || a.XmlPath== "案件信息要素中心/审判/一审/案件审理阶段/详情/证据相关信息/证据/详情/证据内容/详情/证据要素") != null)
                            {
                                if (dataModelFactorList.FirstOrDefault(a => a.XmlPath == "/证据要素" || a.XmlPath == "证据要素" || a.XmlPath == "案件信息要素中心/审判/一审/案件审理阶段/详情/证据相关信息/证据/详情/证据内容/详情/证据要素") != null)
                                {
                                    DataModel dataRoot = dataModelFactorList.FirstOrDefault(a => a.XmlPath == "/证据要素" || a.XmlPath == "证据要素" || a.XmlPath == "案件信息要素中心/审判/一审/案件审理阶段/详情/证据相关信息/证据/详情/证据内容/详情/证据要素");
                                    List<DataModel> dataModelevList = xmlUtilCommon.SubordinateDataModelList(dataModelFactorList, dataRoot);
                                    if (dataModelevList.Count > 1)
                                    {
                                        XmlDocument xmlDocument = xmlUtilCommon.DataModelByXml(dataModelevList, dataRoot.ID);
                                        string xmlout = xmlDocument.OuterXml;
                                        if (!evidData.ContainsKey(keyper))
                                        {
                                            List<Tuple<string, string>> suitdata = new List<Tuple<string, string>>();
                                            suitdata.Add(new Tuple<string, string>(dataModelDetails.AttributesList.FirstOrDefault(a => a.Name == "认定状态").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue, xmlout));
                                            evidData.Add(keyper, suitdata);
                                        }
                                        else
                                        {
                                            evidData[keyper].Add(new Tuple<string, string>(dataModelDetails.AttributesList.FirstOrDefault(a => a.Name == "认定状态").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue, xmlout));
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
            return evidData;
        }
        #endregion

    }
}
